<?php
use \think\response\Json;
use \think\facade\Cache;
// 应用公共文件
if (!function_exists('jsonFail')) {
    /**返回操作失败
     * @param string $msg
     * @param array $data
     * @param int $code
     * @return Json
     */
    function jsonFail($msg = '操作失败', $data = [], $code = 201)
    {
        $compact = compact('code', 'msg', 'data');
        return json($compact);
    }
}

if (!function_exists('jsonSuccess')) {
    /**返回操作成功
     * @param string $msg
     * @param array $data
     * @param int $code
     * @return Json
     */
    function jsonSuccess($msg = '操作成功', $data = [], $code = 200)
    {
        $compact = compact('code', 'msg', 'data');
        return json($compact);
    }
}

if (!function_exists('checkSign')) {
    /**参数验签
     * @param $data
     * @return bool
     */
    function checkSign($data)
    {
        if (!isset($data['nonceStr']) || !isset($data['sign'])) return false;
        $nonceStr = $data['nonceStr']; // 随机码
        unset($data['nonceStr']);
        $sign = $data['sign']; // 签名
        unset($data['sign']);
        ksort($data, SORT_STRING);
        $str = '';
        foreach ($data as $key => $value) {
            if ($key == 'file' || $key == 'image'|| $key == 'pic') continue;
            $str .= "{$key}={$value}&";
        }
        $str .= "nonceStr={$nonceStr}";
        return $sign == md5($str);
    }
}

if (!function_exists('makeToken')) {
    /**生成token
     * @param string $prefix
     * @param string $key
     * @param int $expire
     * @param string $slat
     * @return mixed
     */
    function makeToken($prefix,$key, $expire = 86400,$slat = '')
    {
        $token = $prefix . '-' .sha1(time() . $key . $slat);
        $rtn = Cache::store('redis')->handler()->set($token, $key, $expire);
        if ($rtn) return ['token' => $token, 'expire' => $expire];
        return false;
    }
}

if (!function_exists('getTree')) {
    /**获取树
     * @param $data
     * @param string $idFiled 自身字段
     * @param string $pidFiled 父级字段
     * @return array
     */
    function getTree($data, $idFiled = 'id', $pidFiled = 'pid')
    {
//        static $list = [];
//        foreach ($data as $key => $value) {
//            if ($value[$pidFiled] == $start) {
//                $list[] = $value;
//                unset($data[$key]); //删除已经排好的数据为了减少遍历的次数，当然递归本身就很费神就是了
//                getTree($data,$value[$idFiled]);
//            }
//            var_dump(1);
//        }
//        return $list;
        $items = array_column($data, null, $idFiled);
        $tree = [];
        foreach($items as $k => $item){
//            $items[$k]['children'] = [];
            if(isset($items[$item[$pidFiled]])){
                $items[$item[$pidFiled]]['children'][] = &$items[$k];
            }else{
                $tree[] = &$items[$k];
            }
        }
        return $tree;
    }

    if (!function_exists('makeDualSql')) {
        /**生成dual的sql语句
         * @param $table
         * @param $data
         * @param $where
         * @return string
         */
        function makeDualSql($table,$data, $where)
        {
            $filed = '';
            $select = '';
            foreach ($data as $key => $value) {
                $filed .= "`{$key}`,";
                $select .= "'{$value}',";
            }
            $filed = trim($filed, ',');
            $select = trim($select, ',');
            return "insert into `{$table}` ({$filed}) select {$select} from dual where $where";
        }
    }
    if (!function_exists('checkDatetime')) {
        /**检测是否是合法时间
         * @param $str
         * @param bool $isValidateEmptyStr
         * @param string $format
         * @return bool
         */
        function checkDatetime($str, $isValidateEmptyStr = false ,$format = "Y-m-d H:i:s")
        {
            if ($isValidateEmptyStr == false && $str === '') {
                return true;
            } else if ($isValidateEmptyStr == true && $str == '') {
                return false;
            }
            $time = strtotime($str);  //转换为时间戳
            $checkStr = date($format, $time); //在转换为时间格式
            if($str === $checkStr){
                return true;
            }else{
                return false;
            }
        }
    }
    if (!function_exists('TX_Map_Api_distance')) {
        /*
         * 地图计算距离
         *  $lat1:起点纬度
         *  $lng1 : 起点经度
         *  $lat2:终点纬度
         *  $lng2 : 终点经度
         * */
        function TX_Map_Api_distance($lat1, $lng1, $lat2, $lng2)
        {

            // 将角度转为狐度
            $radLat1 = deg2rad($lat1);// deg2rad()函数将角度转换为弧度
            $radLat2 = deg2rad($lat2);
            $radLng1 = deg2rad($lng1);
            $radLng2 = deg2rad($lng2);

            $a = $radLat1 - $radLat2;
            $b = $radLng1 - $radLng2;

            return 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
        }
    }
    if (!function_exists('create_order_no')) {
        //生成订单号
        function create_order_no()
        {
            return date('Ymd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(1000, 9999));
        }
    }
    if (!function_exists('build_order_no')) {
        //生成子订单号
        /**
         * @return string
         */
        function build_order_no()
        {
             return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        }
    }
    if (!function_exists('Transformation')) {
        /**二维数组转一维数组
         * @param $array
         * @return mixed
         */
        function Transformation($array){
            return array_reduce($array, function ($result, $value) {
                return array_merge($result, array_values($value));
            }, array());//转换得到商户ID
        }
    }
    if(!function_exists('Send_msg')){
        /**
         * @param $plat
         * @param $mobile
         * @param $template
         * @param array $extends
         * @return bool|string
         */
        function Send_msg($plat, $mobile, $template,$extends=[])
        {
            $nonceStr = substr(microtime(), -6);//生成6位
            $data = [
                'plat' => $plat,
                'mobile' => $mobile,
                'template' => $template,
                'extends' => json_encode($extends),
            ];
            ksort($data, SORT_STRING);
            $str = '';
            foreach ($data as $key => $value) {
                $str .= "{$key}={$value}&";
            }
            $str .= "nonceStr={$nonceStr}";
            $data['nonceStr'] = $nonceStr;
            $data['sign'] = md5($str);
            $url = 'http://service.jlxmall.com/shortMsg/send';
            $header = ['Authorization:' . '123456'];
            // curl 初始化
            $curl = curl_init();
            // curl 设置
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            // 判断 $data get  or post
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            // 执行
            $res = curl_exec($curl);
            curl_close($curl);
            return $res;
        }
    }
}